package com.glodon.paas.account.security.oauth1.service;

import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;

import net.oauth.OAuth;
import net.oauth.OAuthAccessor;
import net.oauth.OAuthConsumer;
import net.oauth.OAuthMessage;
import net.oauth.server.OAuthServlet;

import com.glodon.paas.account.security.oauth1.provider.SimpleOAuthProvider;

/**
 * @author: Don Li
 */
public class RequestTokenServlet extends HttpServlet {
	@Autowired
	private SimpleOAuthProvider oauthProvider;
	
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, config.getServletContext());
	}

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        processRequest(request, response);
    }

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        processRequest(request, response);
    }

    private void processRequest(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        try {
            // retrive params for oauth from http request
            OAuthMessage requestMessage = OAuthServlet.getMessage(request, null);
            // get consumer from provider
            OAuthConsumer consumer = oauthProvider.getConsumer(requestMessage);
            // validate accessor with params
            OAuthAccessor accessor = new OAuthAccessor(consumer);
            oauthProvider.VALIDATOR.validateMessage(requestMessage, accessor);
            // get accessor secret
            String secret = requestMessage.getParameter(OAuthConsumer.ACCESSOR_SECRET);
            if (secret != null) {
                accessor.setProperty(OAuthConsumer.ACCESSOR_SECRET, secret);
            }
            // generate request_token and secret
            oauthProvider.generateRequestToken(accessor);
            // write response
            response.setContentType("text/plain");
            OutputStream out = response.getOutputStream();
            OAuth.formEncode(OAuth.newList("oauth_token", accessor.requestToken, "oauth_token_secret", accessor.tokenSecret), out);
            out.close();
        } catch (Exception e) {
        	oauthProvider.handleException(e, request, response, true);
        }
    }
}
